package com.`as`.common

import android.content.ContentResolver
import android.content.Context
import android.provider.Settings
import android.view.Window
import androidx.annotation.IntRange

/**
 * descrition:
 */
/**
 * 获取屏幕亮度
 *
 * @return 屏幕亮度 0-255
 */
fun Context.getBrightness(): Int {
    return try {
        Settings.System.getInt(
            contentResolver,
            Settings.System.SCREEN_BRIGHTNESS
        )
    } catch (e: Settings.SettingNotFoundException) {
        e.printStackTrace()
        0
    }
}

/**
 * 设置屏幕亮度
 *
 * 需添加权限 `<uses-permission android:name="android.permission.WRITE_SETTINGS" />`
 * 并得到授权
 *
 * @param brightness 亮度值
 */
fun Context.setBrightness(@IntRange(from = 0, to = 255) brightness: Int): Boolean {
    val resolver: ContentResolver = contentResolver
    val b = Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, brightness)
    resolver.notifyChange(Settings.System.getUriFor("screen_brightness"), null)
    return b
}

/**
 * 设置窗口亮度
 *
 * @param window     窗口
 * @param brightness 亮度值
 */
fun setWindowBrightness(
    window: Window,
    @IntRange(from = 0, to = 255) brightness: Int
) {
    val lp = window.attributes
    lp.screenBrightness = brightness / 255f
    window.attributes = lp
}

/**
 * 获取窗口亮度
 *
 * @param window 窗口
 * @return 屏幕亮度 0-255
 */
fun Context.getWindowBrightness(window: Window): Int {
    val lp = window.attributes
    val brightness = lp.screenBrightness
    return if (brightness < 0) getBrightness() else (brightness * 255).toInt()
}
